package net.xxcl.kygl.controller;

import net.xxcl.kygl.pojo.*;
import net.xxcl.kygl.service.JtpsyjService;
import net.xxcl.kygl.service.ProjectService;
import net.xxcl.kygl.service.ProjectTypeService;
import net.xxcl.kygl.service.SbpsyjService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * User: 夏汛
 * Date: 12-5-29
 * Time: 下午3:23
 */
@Controller
@RequestMapping("/file")
public class FileController {
    @Autowired
    private ProjectService projectService;
    @Autowired
    private ProjectTypeService projectTypeService;
    @Autowired
    private SbpsyjService sbpsyjService;
    @Autowired
    private JtpsyjService jtpsyjService;

    /**
     * 查看课题材料
     * @param projectid
     * @param request
     * @param response
     */
    @RequestMapping(value = "/download")
    public void download(@RequestParam("projectid") Integer projectid,
                         HttpServletRequest request,HttpServletResponse response){
        try{
            String filename = URLDecoder.decode(request.getParameter("filename"),"utf-8");
            Project project = projectService.selectByPrimaryKey(projectid);
            String filePath = project.getFilepath();
            if(!(filePath.equals("") || filename.equals(""))){
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;fileName=" +
                        new String(filename.getBytes(),"ISO-8859-1"));
                File file=new File(request.getSession().getServletContext().getRealPath("/") + filePath + filename);
                //response.addHeader("Content-Length", "" + file.length());
                if(file.exists()){
                    InputStream inputStream=new FileInputStream(file);
                    OutputStream os=response.getOutputStream();
                    byte[] b=new byte[512];
                    int length;
                    while((length=inputStream.read(b))>0){
                        os.write(b,0,length);
                    }
                    inputStream.close();
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 申报评审专家意见
     * @param projectid
     * @param request
     * @param response
     */
    @RequestMapping(value = "/sbpsyj")
    public void sbpsyj(@RequestParam("projectid") Integer projectid,
                         HttpServletRequest request,HttpServletResponse response){
        try{
            Project project = projectService.selectByPrimaryKey(projectid);
            Criteria criteria = new Criteria();
            criteria.put("projectid",projectid);
            criteria.put("isleader",1);
            List<Sbpsyj> sbpsyjs = sbpsyjService.selectByExample(criteria);

            String filePath = project.getFilepath();
            String filename = sbpsyjs.get(0).getYjpath();

            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" +
                    new String(filename.getBytes(),"ISO-8859-1"));
            File file=new File(request.getSession().getServletContext().getRealPath("/") + filePath + filename);
            if(file.exists()){
                InputStream inputStream=new FileInputStream(file);
                OutputStream os=response.getOutputStream();
                byte[] b=new byte[512];
                int length;
                while((length=inputStream.read(b))>0){
                    os.write(b,0,length);
                }
                inputStream.close();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 申报评审专家意见
     * @param projectid
     * @param request
     * @param response
     */
    @RequestMapping(value = "/jtpsyj")
    public void jtpsyj(@RequestParam("projectid") Integer projectid,
                       HttpServletRequest request,HttpServletResponse response){
        try{
            Project project = projectService.selectByPrimaryKey(projectid);
            Criteria criteria = new Criteria();
            criteria.put("projectid",projectid);
            criteria.put("isleader",1);
            List<Jtpsyj> jtpsyjs = jtpsyjService.selectByExample(criteria);

            String filePath = project.getFilepath();
            String filename = jtpsyjs.get(0).getYjpath();

            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" +
                    new String(filename.getBytes(),"ISO-8859-1"));
            File file=new File(request.getSession().getServletContext().getRealPath("/") + filePath + filename);
            if(file.exists()){
                InputStream inputStream=new FileInputStream(file);
                OutputStream os=response.getOutputStream();
                byte[] b=new byte[512];
                int length;
                while((length=inputStream.read(b))>0){
                    os.write(b,0,length);
                }
                inputStream.close();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 批量上传
     * @param request
     * @param response
     */
    @RequestMapping(value = "/upload")
    public void save(MultipartHttpServletRequest request,HttpServletResponse response){
        MultipartFile file = request.getFile("file");
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = null;
        try{
            int projectId = Integer.parseInt(request.getParameter("projectId"));
            Project project = projectService.selectByPrimaryKey(projectId);
            String filepath = project.getFilepath();

            if(filepath==null){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年");
                ProjectType projectType = projectTypeService.selectByPrimaryKey(project.getProjecttype());
                if(projectType.getIscross()){
                    filepath = "upload" + File.separator
                            + sdf.format(new Date()) + File.separator + "科研课题" + File.separator
                            + "横向课题" + File.separator + UUID.randomUUID() + File.separator + project.getName()
                            + File.separator;
                } else if(projectType.getId()==1 || projectType.getId()==2){
                    filepath = "upload" + File.separator + sdf.format(project.getApprovaltime()) + File.separator
                            + "科研课题" + File.separator + "院级课题" + File.separator + UUID.randomUUID()
                            + File.separator + project.getName() + File.separator;
                } else {
                    filepath = "upload" + File.separator + sdf.format(project.getApprovaltime()) + File.separator
                            + "科研课题" + File.separator + projectType.getName() + File.separator + UUID.randomUUID()
                            + File.separator + project.getName() + File.separator;
                }
                project.setFilepath(filepath);
                projectService.updateByPrimaryKeySelective(project);
            }

            String existFileName = project.getFilename();
            SimpleDateFormat sdf = new SimpleDateFormat("-yyyy-MM-dd");
            String fileDate = sdf.format(new Date());
            out = response.getWriter();
            if(!file.isEmpty()){
                String fileTrueName = file.getOriginalFilename();
                int ch = fileTrueName.lastIndexOf(".");
                String fileName = fileTrueName.substring(0,ch) + fileDate + fileTrueName.substring(ch);
                File saveFile = new File(request.getSession().getServletContext().getRealPath("/") +
                        filepath + fileName);
                FileUtils.writeByteArrayToFile(saveFile, file.getBytes());
                if(existFileName==null){
                    project.setFilename(fileName);
                    projectService.updateByPrimaryKeySelective(project);
                } else if(!existFileName.contains(fileName)){
                    existFileName += ":" + fileName;
                    project.setFilename(existFileName);
                    projectService.updateByPrimaryKeySelective(project);
                }
            }
            out.print("{'success':true}");
        } catch (IOException e){
            e.printStackTrace();
            out.print("{'success':false}");
        }
    }
}
